var bridge={
    port:null,
    options:{},
    event:{},
    trigger:(name,msg)=>{
         bridge.port.postMessage({event:name,data:msg});
    },
    on:(type,func)=>{
        if(typeof type ==='object') {
            for(let k in type) bridge.on(k,type[k]);
            return true;
        }
        if(bridge.port[type])
                bridge.port[type].addListener(func);
        else{
            bridge.event[type]=func;
        }
    },
    init:(p)=>{
        bridge.port=chrome.runtime.connect();
        bridge.port.onMessage.addListener(function(msg){
                if(msg.options) bridge.options = msg.options;
                if(msg.event){
                        bridge.event[msg.event](msg.data);
                }
        });
      
       bridge.on('changeOptions',(opt)=>{
           for(let n in opt )     bridge.options[n]=opt[n];
       })
       //事件
       if(p){
           bridge.on(p);
           bridge.trigger('init');
       }
    },
    loads:(fs)=>{
        fs.forEach(bridge.include)
    },
    include:(f)=>{
            let e=null,url=chrome.runtime.getURL(f);
            switch(f.replace(/.+\./,'')){
                case "js": 
                    e=document.createElement('script');
                    e.src=url;
                    break;
                case 'css':
                    e=document.createElement('link');
                    e.href=url;
                    e.type="text/css";
                    e.rel="stylesheet";
                    break;
            }
            document.head.append(e);
    }
};

function processData(type,data){
    if (window != top || !bridge.options.autoJsonParse) return;
    if (bridge.options.safeMethod) {
            xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                    if (this.readyState == 4) {
                                    data = this.responseText;
                                    bridge.trigger(type, data);
                    }
            };
            xhr.open("GET", document.location.href, true);
            xhr.send(null);
    } else if (data) {
            bridge.trigger(type, data);
    }
}

function initJsonParse(data) {
    bridge.init();
    bridge.on({
        "init": function (options) {
            processData("loadJson",data);
        },
        success: function () {
                //window.options=bridge.options;
                document.head.innerHTML='<link rel="stylesheet" type="text/css" href="' + chrome.runtime.getURL("json.css") + '">';   
                document.body.innerHTML =json.get(data);
                if(bridge.options.enableFold) json.addCloseButton(document.body);
        },
        error: function (d) {
            console.log(d);
        }
    });
    bridge.trigger('init')
}


function initKeyDownBind(){
     bridge.init({
             init: function (options) {
                 if(!options.autoBaiduBind) return;
                ["baidu.css","lib/keycode_alias.js","lib/baidu_keymap.js"].forEach(bridge.include)
            },
     });
}

function load() {
	var child, data,text;
	if (document.body && (document.body.childNodes[0] && document.body.childNodes[0].tagName == "PRE" || document.body.children.length == 0)) {
		child = document.body.children.length ? document.body.childNodes[0] : document.body;
                                           text= child.innerText;
		if (((text.charAt(0) == "[" && text.charAt(text.length - 1) == "]") || (text.charAt(0) == "{" && text.charAt(text.length - 1) == "}"))) initJsonParse(child.innerText);
	}else if(document.URL.match(/https:..www.baidu.com.s/) ) {
                         initKeyDownBind();
                    }
}

load();
